package com.example.administrator.u17.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.administrator.u17.R;
import com.example.administrator.u17.adapter.PaihangFragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/14.
 */

public class PaiHangFragment extends Fragment implements TabLayout.OnTabSelectedListener {

    private TabLayout mTab;
    private ViewPager vp;
    private String[] titles = {"月票", "点击", "吐槽", "新作"};
    private List<Fragment> fragmentList;
    private PaihangFragmentPagerAdapter mAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.paihangfragment, null);
        initView(view);
        initData();
        setData();
        setlistener();
        return view;
    }

    private void setlistener() {
        mTab.addOnTabSelectedListener(this);
    }

    private void setData() {
        vp.setAdapter(mAdapter);
        mTab.setupWithViewPager(vp);
        mTab.setTabTextColors(Color.BLACK, Color.GREEN);
        mTab.setSelectedTabIndicatorColor(Color.GREEN);
        mTab.setSelectedTabIndicatorHeight(5);
    }

    private void initData() {
        fragmentList = new ArrayList<>();
        fragmentList.add(new YuepiaoFragment());
        fragmentList.add(new ClickFragment());
        fragmentList.add(new TuCaoFragment());
        fragmentList.add(new NewZuoFragmet());
        mAdapter = new PaihangFragmentPagerAdapter(getActivity().getSupportFragmentManager(), fragmentList, titles);
    }

    private void initView(View view) {
        mTab = (TabLayout) view.findViewById(R.id.tab_paihang_fragment);
        vp = (ViewPager) view.findViewById(R.id.vp_paihang_fragment);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        for (int i = 0; i < mTab.getTabCount(); i++) {
            if (mTab.getTabAt(i) == tab) {
                FragmentTransaction transaction = getActivity().
                        getSupportFragmentManager().beginTransaction();
                vp.setCurrentItem(i);
                transaction.addToBackStack(null);
                transaction.commit();
                break;
            }
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }
}